package com.apes.framework.query.lib;

import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apestech.api.query.sys.SysSql;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.MakeCondition;
import com.apestech.framework.util.DBUtil;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.xml.XmlUtil;
import com.apestech.framework.xml.plugin.modul.QryConfig;
import com.apestech.framework.xml.sql.SqlNodeVar;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * @author hup
 * @create 2019-02-15-9:39
 */
public class PubToolUtil extends StringUtil {

    private static JSONObject conKey=new JSONObject();
    private static JSONObject conCount=new JSONObject();

    public static Connection getCon(String key) {
        return (Connection) conKey.get(key);
    }

    public static void setConKey(String key, Connection connection) throws Exception {
        conKey.put(key, connection);
        Integer i=conCount.getInteger(key);
        if(i==null) i=0;
        i++;
        conCount.put(key, i);
    }

    public static void closeConKey(String key) throws Exception {
        if(key==null) return;
        Connection conn=getCon(key);
        if(conn!=null){
            Integer i=conCount.getInteger(key);
            if(i==1){
                conn.close();
                removeConKey(key);
            } else {
                i--;
                conCount.put(key, i);
            }
        }
    }

    private static void removeConKey(String key){
        conKey.remove(key);
    }

    public static JSONObject getInput(SimpleRequest param) throws Exception {
        Object body=param.getData();
        JSONObject input=null;
        if(body instanceof String){
            input=JSON.toJSON(body);
        } else {
            input=new JSONObject((Map)body);
        }
        input.put("method", param.getRopRequestContext().getMethod());
        JPAInput jinput=new JPAInput(input);
        return jinput.getData();
    }

    public static String getDBName(){
        return DBUtil.getSysSingleDBName("ESB");
    }

    public static SqlSession getSession(Connection connection) throws Exception {
        if(connection==null){
            throw new Exception("当前服务器，没有可用连接！");
        }
        SqlSession session=DBUtil.getSession(getDBName());
        session.setConnection(connection);
        return session;
    }

    public static SqlSession getSession_S() throws Exception {
        SqlSession session=DBUtil.getSession(getDBName());
        return session;
    }

    public static SqlSession getSession(String sysId, Connection connection) throws Exception {
        if(sysId==null || sysId.equals(getDBName())){
            return getSession(connection);
        } else {
            return getNSession(sysId, connection);
        }
    }

    public static SqlSession getNSession(String sysId, Connection connection) throws Exception {
        if(connection==null){
            throw new Exception("当前服务器，没有可用连接！");
        } else {
            throw new Exception("当前服务器，不允许跨库操作");
        }
//        DBUtil.getDataSource(sysId);
//        SqlSession session=DBUtil.getSession(sysId);
//        return session;
    }

    public static QryConfig getQryConfig(String queryId) throws Exception {
        QryConfig config=null;
        if(queryId==null){
            config=new QryConfig();
            config.setSqlCallback(new BaseSqlCallBack());
        } else {
            config= XmlUtil.getQueryConfig(queryId);
        }
        return config;
    }

    public static JSONObject getAssociateJson(JSONObject param) throws Exception {
        if(param==null){
            return null;
        }
        JSONObject map=new JSONObject();
        ArrayList<String> klist=param.getKeylist();
        int len=klist.size();
        JSONArray con=new JSONArray();
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            Object obj=param.get(k);
            if(obj instanceof Map){
                if("group".equals(k) || "domain".equals(k)){
                    obj=JSON.toJSON(obj).get("filters");
                    JSONArray list=JSON.toJSONArray(obj);
                    int jlen=list.size();
                    for(int j=0; j<jlen; j++){
                        JSONObject m=list.get(j);
                        if("EQ".equals(m.getString("operator"))){
                            map.put(m.getString("field"), m.get("value"));
                        } else {
                            con.add(m);
                        }
                    }
                }
            } else {
                map.put(k, obj);
            }
        }
        if(con.size()>0){
            map.put("condition", con);
        }
        return map;
    }

    public static JSONObject getRole(JSONObject json, String postId) throws Exception {
        json.put("postId", postId);
        if(json.get("nativeAuth")==null) return json;  //|| !json.getBoolean("nativeAuth")
        JSONArray list=JSON.toJSONArray(json.get("nativeAuth"));
        JSONObject m= SysSql.getRole("ESB", list, postId, null);
        if(m==null) m=new JSONObject();
        json.remove("nativeAuth");
        json.put("othersql", m.get("auth"));
        ArrayList<String> klist=m.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String key=klist.get(i);
            if(!"auth".equals(key)){
                if(json.get(key)==null) json.put(key, SqlNodeVar.getInnerValue());
            }
        }
        return json;
    }

    public static JSONObject getDateField(JSONObject row){
        if(row==null) return null;
        ArrayList<String> klist=row.getKeylist();
        int len=klist.size();
        for(int i=0; i<len; i++){
            String k=klist.get(i);
            Object value=row.get(k);
            if(value instanceof Date){
                row.put(k, DateUtil.dateTimeToStr((Date)value));
            }
        }
        return row;
    }

}
